package monitor

import (
	"fmt"
	"gitee.com/guolianyu/kit/skit/third_party/config"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/transport/http"
	"github.com/go-kratos/kratos/v2/transport/http/pprof"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func NewPProfServer(c *config.PprofServer) *http.Server {
	if c == nil || c.Enabled == false {
		return nil
	}
	if c.Port <= 0 {
		c.Port = 6060 //默认端口
	}
	var opts = []http.ServerOption{
		http.Address(fmt.Sprintf("%s:%d", c.Host, c.Port)),
		http.Middleware(
			recovery.Recovery(),
		),
	}
	srv := http.NewServer(opts...)

	//metrics
	if c.EnableMetrics {
		//enable prometheus global switch
		srv.Handle("/metrics", promhttp.Handler())
	}

	//pprof 这边引用的是  "net/http/pprof" 这个原生包，这边需要手动输入路由才能访问
	//if c.EnablePprof {
	//	srv.HandleFunc("/debug/pprof", pprof.Index)
	//	srv.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
	//	srv.HandleFunc("/debug/pprof/profile", pprof.Profile)
	//	srv.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
	//	srv.HandleFunc("/debug/pprof/trace", pprof.Trace)
	//}

	//这边引用的是 kratos的pprof包，这边可以直接点击访问链接
	if c.EnablePprof {
		srv.HandlePrefix("/", pprof.NewHandler())
		srv.Handle("/debug/pprof", pprof.NewHandler())
		srv.Handle("/debug/pprof/cmdline", pprof.NewHandler())
		srv.Handle("/debug/pprof/profile", pprof.NewHandler())
		srv.Handle("/debug/pprof/symbol", pprof.NewHandler())
		srv.Handle("/debug/pprof/trace", pprof.NewHandler())
	}

	return srv
}
